/**
 * @FileName: RegisterActivity.java
 * @Package:com.bdtop.dbl.ui.activities.acccount
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-15
 * @version V1.0
 */

package com.bdtop.dbl.ui.activities.acccount;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bdtop.dbl.BaseActivity;
import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.R;
import com.bdtop.dbl.server.ServerApiFactory;
import com.bdtop.dbl.server.response.BaseResponse;
import com.bdtop.dbl.server.response.LoginResponse;
import com.bdtop.dbl.thirdparty.asynchttp.RequestCallback;
import com.bdtop.dbl.ui.activities.main.MainActivity;
import com.bdtop.dbl.ui.view.TitleBar;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.NetworkUtils;
import com.bdtop.dbl.utils.Preferences;

/**
 * @ClassName: RegisterActivity
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-15
 */
public class RegisterActivity extends BaseActivity {

	private TitleBar mTitleBar;
	private EditText mPhoneText;
	private Button mOKBtn;
	private Button mLoginBtn;

	public static final void launch(Context context) {
		Intent intent = new Intent(context, RegisterActivity.class);
		context.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_register);
		initViews();

		findViewById(R.id.tx_look).setOnClickListener(mOnClickListener);
	}

	private void initViews() {
		mTitleBar = (TitleBar) findViewById(R.id.title_bar);
		mTitleBar.setTitle(R.string.register_title);
		mTitleBar.setBackShowOrHidden(View.GONE);
		mPhoneText = (EditText) findViewById(R.id.phone_number_view);

		mOKBtn = (Button) findViewById(R.id.ok);
		mOKBtn.setOnClickListener(mOnClickListener);

		mLoginBtn = (Button) findViewById(R.id.login);
		mLoginBtn.setOnClickListener(mOnClickListener);
	}

	private OnClickListener mOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.ok:
				String value = mPhoneText.getText().toString().trim();
				if (TextUtils.isEmpty(value)) {
					showToast(R.string.mobile_format_2);
				} else if (value.length() != 11) {
					showToast(R.string.mobile_format);
				} else {
					String phoneNumber = mPhoneText.getText().toString().trim();
					ServerApiFactory.getApiImpl().register(phoneNumber, mRegisterCallback);
					showWaitingDialog(R.string.waiting_get_code, false, true);
				}
				break;

			case R.id.login:
				LoginActivity.launch(RegisterActivity.this);
				finish();
				break;
			case R.id.tx_look:
				clearLoginParams();
				loginTestUser();
				break;
			default:
				break;
			}
		}
	};

	private RequestCallback mRegisterCallback = new RequestCallback() {

		@Override
		public void onSuccess(String rawData, Object response) {
			BaseResponse baseResponse = (BaseResponse) response;
			
			if (Constants.REQUEST_SUCCESS.equalsIgnoreCase(baseResponse.getStatus())) {
				showToast(baseResponse.getDesc());
				VerifyPhoneNumberActivity.launch(RegisterActivity.this, mPhoneText.getText().toString());
			}else{
				showWrongDialog(baseResponse.getDesc());
			}
			dismissDialog();
		}

		@Override
		public void onError(int statusCode, Throwable e, String rawData) {
			dismissDialog();
			if (NetworkUtils.isNetConnect(getApplicationContext())) {
				showToast(R.string.oper_error);
			} else {
				showToast(R.string.net_error);
			}
		}
	};

	private long exitTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(getApplicationContext(), R.string.exit_app_tip, Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
				DBLApplication.getInstance().exit();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void clearLoginParams() {
//		String username = Preferences.getUserName(this);
//		Preferences.saveUserName(this, "");
//		Preferences.savePassword(this, "");
//		Preferences.setAutoLogin(this, false);
//		Preferences.setRememberPwd(this, false);
//		Preferences.saveLoginStatus(this, false);
//		Preferences.saveLastLoginUser(this, username);
//
//		DBLApplication.getInstance().deviceInfoList = null;
//		DBLApplication.getInstance().currentDi = null;
		
		String username = Preferences
				.getUserName(this);
		// fix: 注销 保留 账号密码
//		Preferences.saveUserName(getActivity(), "");
//		Preferences.savePassword(getActivity(), "");
//		Preferences.setRememberPwd(getActivity(), false);
		
		// fix: 一次性commit
		// Preferences.setAutoLogin(getActivity(), false);
		// Preferences.saveLoginStatus(getActivity(), false);
		// Preferences.saveLastLoginUser(getActivity(),username);
		
//		Editor editor = Preferences.getPreferences(this).edit();
//		editor.putBoolean(Preferences.AUTO_LOGIN, false);
//		editor.putBoolean(Preferences.ISLOGIN, false);
//		editor.putString(Preferences.LAST_LOGIN_USER, username);
//		editor.commit();
		// fix: db
		Preferences.clearLoginParams(username);
		

		DBLApplication.getInstance().deviceInfoList = null;
		DBLApplication.getInstance().currentDi = null;
	}

	private void loginTestUser() {
		showWaitingDialog(R.string.waiting_login, false, true);

		ServerApiFactory.getApiImpl().login(Constants.TEST_PHONE, Constants.TEST_PWD, new RequestCallback() {
			@Override
			public void onSuccess(String rawData, Object response) {
				LoginResponse loginResponse = (LoginResponse) response;

				String status = loginResponse.getStatus();
				String desc = loginResponse.getDesc();

				if (Constants.REQUEST_SUCCESS.equals(status)) {
					// Login success, need store the "sign" for other request.
					Preferences.saveLoginSign(RegisterActivity.this, loginResponse.getSign());
					MainActivity.launch(RegisterActivity.this);
					finish();
				} else {
					Toast.makeText(RegisterActivity.this, desc, Toast.LENGTH_LONG).show();
				}
				dismissDialog();
			}

			@Override
			public void onError(int statusCode, Throwable e, String rawData) {
				dismissDialog();
				if (NetworkUtils.isNetConnect(getApplicationContext())) {
					showToast(R.string.oper_error);
				} else {
					showToast(R.string.net_error);
				}
			}
		});
	}
	
	
	private void showWrongDialog(String text) {
		final Dialog d = new Dialog(RegisterActivity.this, R.style.Theme_Light_NoTitle_Dialog);
		d.setCancelable(true);
		d.setCanceledOnTouchOutside(true);

		View content = LayoutInflater.from(RegisterActivity.this).inflate(R.layout.dialog_confirm_2, null);

		content.findViewById(R.id.btn_cancel).setVisibility(View.GONE);
		content.findViewById(R.id.btn_divider).setVisibility(View.GONE);
		TextView txMessage = (TextView) content.findViewById(R.id.tx_message);
		txMessage.setText(text);
		
		content.findViewById(R.id.btn_confirm).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				if(d != null){
					d.dismiss();
				}
			}
		});

		d.setContentView(content);
		d.show();
	}
}
